//
//  ViewController.m
//  PhotoDemo
//
//  Created by LiynXu on 2016/10/28.
//  Copyright © 2016年 LiynXu. All rights reserved.
//

#import "ViewController.h"
#import "CameraViewController.h"

@interface ViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
@property (strong, nonatomic) IBOutlet UIButton *photoButton;
@property (strong, nonatomic) IBOutlet UIButton *camButton;
@property (strong, nonatomic) UIImagePickerController *imagePiker;
@property (nonatomic, strong) NSMutableArray *photoArray;
@property (nonatomic,strong) NSMutableArray *orginalPhotoArray;
@property (nonatomic,strong) PHFetchResult *smartAlbums;
@property (nonatomic,strong) PHImageRequestOptions *requestOption;
@property (nonatomic,strong) UIActionSheet *sheet;
@end

@implementation ViewController
-(UIActionSheet *)sheet{
    if (_sheet == nil) {
        _sheet = [[UIActionSheet alloc] initWithTitle:@"图片选择方式" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相册",@"相机", nil];
        _sheet.actionSheetStyle = UIActionSheetStyleAutomatic;
    }
    return _sheet;
}
-(NSMutableArray *)orginalPhotoArray{
    if (_orginalPhotoArray == nil) {
        _orginalPhotoArray = [NSMutableArray array];
    }
    return  _orginalPhotoArray;
}
-(PHImageRequestOptions *)requestOption{
    if (_requestOption == nil) {
        _requestOption = [[PHImageRequestOptions alloc] init];
        _requestOption.resizeMode = PHImageRequestOptionsResizeModeExact;
        _requestOption.synchronous = YES;
        _requestOption.deliveryMode = PHImageRequestOptionsDeliveryModeFastFormat;
    }
    return _requestOption;
}

-(UIImagePickerController *)imagePiker{
    if (_imagePiker == nil) {
        _imagePiker = [[UIImagePickerController alloc]init];
        _imagePiker.delegate = self;
        // 设置是否需要做图片编辑，default NO
        _imagePiker.allowsEditing = NO;
        
    }
    return _imagePiker;
}
-(NSMutableArray *)photoArray{
    if (_photoArray == nil) {
        _photoArray = [[NSMutableArray alloc] init];
    }
    return _photoArray;
}
/*
 PHImageRequestOptions有以下几个重要的属性：
 
 synchronous：指定请求是否同步执行。
 resizeMode：对请求的图像怎样缩放。有三种选择：None，不缩放；Fast，尽快地提供接近或稍微大于要求的尺寸；Exact，精准提供要求的尺寸。
 deliveryMode：图像质量。有三种值：Opportunistic，在速度与质量中均衡；HighQualityFormat，不管花费多长时间，提供高质量图像；FastFormat，以最快速度提供好的质量。
 这个属性只有在 synchronous 为 true 时有效。
 normalizedCropRect：用于对原始尺寸的图像进行裁剪，基于比例坐标。只在 resizeMode 为 Exact 时有效。
 */
-(PHFetchResult *)smartAlbums{
    
    if (_smartAlbums == nil) {
        _smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeSmartAlbumUserLibrary options:nil];
    }
    return _smartAlbums;
}

-(void)viewWillAppear:(BOOL)animated{
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationSlide];
    self.navigationController.navigationBar.hidden = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction)photo:(id)sender {
    
    [self initPhotoData];
    
    PhotoViewController *photoVC = [[PhotoViewController alloc] init];
    [photoVC setThumbnailImagesArrayWithArray:self.photoArray];
    
    __weak typeof(self) weakSelf = self;
    
    [photoVC setPhotoBlock:^(NSDictionary *dictionary) {
        [weakSelf parseData:dictionary];
    }];
    
    [self.navigationController pushViewController:photoVC animated:YES];
    
}

/// 初始化相册数据
- (void)initPhotoData{
    [self.photoArray removeAllObjects];
    __weak typeof(self) weakSelf = self;
    for (PHCollection * obj in self.smartAlbums) {
        if ([obj isKindOfClass:[PHAssetCollection class]]) {
            PHAssetCollection *collection = (PHAssetCollection *)obj;
            PHFetchOptions *options = [[PHFetchOptions alloc] init];
            options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
            PHFetchResult *fetchReuslt  = [PHAsset fetchAssetsInAssetCollection:collection options:options];
            NSLog(@"count - %ld",(unsigned long)fetchReuslt.count);
            if (fetchReuslt.count == 0) {
                continue;
            }
            NSInteger count = 20<fetchReuslt.count?20:fetchReuslt.count;
            __block NSInteger _index = 0;
            for (NSInteger i = 0 ;i<count;i++) {
                PHAsset *asset  = fetchReuslt[i];
                //使用PHImageManager从PHAsset中请求图片
                NSInteger index = _index;
                MyImageManager *imageManager = [MyImageManager defaultManager];
                [imageManager requestImageForAsset:asset targetSize:CGSizeMake(ItemWidth()*2-2, ItemHieght()*2-2) contentMode:PHImageContentModeAspectFill options:self.requestOption Index:index resultHandler:^(UIImage *result, NSDictionary *info, NSInteger index) {
                    NSInteger IDKey = [info[@"PHImageResultRequestIDKey"] integerValue];
                    NSLog(@"%@,%ld,%ld,%ld",result,(long)IDKey,index,IDKey-index);
                    [weakSelf.photoArray addObject:result];
                }];
                _index++;
            }
        }else{
            NSLog(@"NO");
            NSAssert1(NO, @"Fetch Collect Not PHCollection:%@", obj);
        }
    }
    NSLog(@"initPhotoDataDone");
}

- (void)parseData:(NSDictionary *)dictionary{
    [self.orginalPhotoArray removeAllObjects];
    NSLog(@"%@",dictionary);
    __weak typeof(self) weakSelf = self;
    for (PHCollection * obj in self.smartAlbums) {
        if ([obj isKindOfClass:[PHAssetCollection class]]) {
            PHAssetCollection *collection = (PHAssetCollection *)obj;
            PHFetchOptions *options = [[PHFetchOptions alloc] init];
            options.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO]];
            PHFetchResult *fetchReuslt  = [PHAsset fetchAssetsInAssetCollection:collection options:options];
            NSInteger count = dictionary.allKeys.count;
            for (NSInteger i = 0 ;i<count;i++) {
                NSInteger index = [dictionary.allKeys[i] integerValue];
                PHAsset *asset  = fetchReuslt[index];
                //使用PHImageManager从PHAsset中请求图片
                MyImageManager *imageManager = [MyImageManager defaultManager];
                [imageManager requestImageForAsset:asset targetSize:PHImageManagerMaximumSize contentMode:PHImageContentModeAspectFill options:self.requestOption resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
                    [weakSelf.orginalPhotoArray addObject:result];
                }];
            }
        }else{
            NSLog(@"NO");
            NSAssert1(NO, @"Fetch Collect Not PHCollection:%@", obj);
        }
    }
    NSLog(@"%@",self.orginalPhotoArray);
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        PhotoViewController *photoVC = [[PhotoViewController alloc] init];
//        [photoVC setThumbnailImagesArrayWithArray:self.orginalPhotoArray];
//        [photoVC setPhotoBlock:^(NSDictionary *dictionary) {
//            [weakSelf parseData:dictionary];
//        }];
//        [self.navigationController pushViewController:photoVC animated:YES];
//    });
    
}
#pragma mark - 相机
- (IBAction)cam:(id)sender {
    
    __weak typeof(self) weakSelf = self;
    
    CameraViewController *cam = [[CameraViewController alloc] init];
    [cam setImageblock:^(NSDictionary *imageDictionary) {
        [weakSelf.orginalPhotoArray addObject:imageDictionary];
    }];
    
    if (![self isCameraAvailable]) {
        NSLog(@"相机不可用");
        return;
    }
    NSLog(@"相机可用");
    
    self.navigationController.navigationBar.hidden = YES;
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationSlide];
    [self.navigationController pushViewController:cam animated:YES];
}



// 判断设备是否有摄像头
- (BOOL) isCameraAvailable{
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

- (IBAction)ModePresent:(UIButton *)sender {
    
    [self.sheet showInView:self.view];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"%ld",buttonIndex);
    switch (buttonIndex) {
        case 0:{
            [self photo:nil];
        }
            break;
        case 1:{
            [self cam:nil];
        }
        default:
            break;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSLog(@"ReceiveMemoryWarning");
    // Dispose of any resources that can be recreated.
}

@end
